package yazan.com.pdacollector_android.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.maning.mndialoglibrary.MProgressDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import yazan.com.pdacollector_android.R;
import yazan.com.pdacollector_android.adapter.OrderDetailAdapter;
import yazan.com.pdacollector_android.base.BaseActivity;
import yazan.com.pdacollector_android.base.Presenter;
import yazan.com.pdacollector_android.model.Goods;
import yazan.com.pdacollector_android.model.OrderInfo;
import yazan.com.pdacollector_android.presenter.OrderPresenter;
import yazan.com.pdacollector_android.utils.MProgressDialogHelper;
import yazan.com.pdacollector_android.utils.PDAGlobal;
import yazan.com.pdacollector_android.utils.ScanDeviceHelper;

public class OrderDetailActivity extends BaseActivity {
    //<editor-fold desc=”成员变量”>

    private static final int RESULT_CODE = 652;

    @BindView(R.id.etUniqueID)
    EditText etUniqueID;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.btValidation)
    Button btValidation;
    @BindView(R.id.tvSuccessCount)
    TextView tvSuccessCount;
    @BindView(R.id.btDone)
    Button btDone;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.hiddenEt)
    EditText hiddenEt;


    private OrderDetailAdapter orderDetailAdapter;

    private int pageIndex = 0;

    private ScanDeviceHelper scanDeviceHelper;

    private OrderInfo mOrderInfo = null;

    private boolean uniqueIDLock = false;

    //</editor-fold>

    //<editor-fold desc=”生命周期”>


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);
        ButterKnife.bind(this);
        configUI();

        scanDeviceHelper = new ScanDeviceHelper(this, new ScanValidationListener(this));
    }

    @Override
    protected void onStart() {
        super.onStart();
        scanDeviceHelper.registerReceiver();
    }

    @Override
    protected void onStop() {
        super.onStop();
        scanDeviceHelper.unRegisterReceiver();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PDAGlobal.selectPosition = -1;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == RESULT_CODE) {
            if (resultCode == 1) {
                Goods target = data.getParcelableExtra("good");
                if (target != null) {
                    int position = 0;
                    for (int i = 0; i < orderDetailAdapter.getData().size(); i++) {
                        Goods good = orderDetailAdapter.getData().get(i);
                        if (good.getFgoods_sn() != null && good.getFgoods_sn().equals(target.getFgoods_sn())
                                && good.getFIndex() == target.getFIndex()
                        ) {
                            good.setValidation_type(target.getValidation_type());
                            good.setValidation_count(target.getValidation_count());
                            good.setFgoods_codes(target.getFgoods_codes());
                            position = i;
                            statisticsSuccessCount();
                            break;
                        }
                    }
                    orderDetailAdapter.notifyItemChanged(position);
                }
            }
        }
    }


    //</editor-fold>


    //<editor-fold desc=”私有方法”>

    @SuppressLint("SetTextI18n")
    private void configUI() {
        long Forder_id = getIntent().getLongExtra("Forder_id", -1);
        if (Forder_id != -1) {
            setUniqueID(Forder_id + "");
        }

        etUniqueID.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    unlockEtUnique();
                }
            }
        });

        etUniqueID.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.d("aaaa", "afterTextChanged: " + s);
                resetData();
            }
        });

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        orderDetailAdapter = new OrderDetailAdapter(R.layout.item_order_detail, null, this);
        orderDetailAdapter.bindToRecyclerView(recyclerView);
        orderDetailAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Log.d("aaaaa", "onItemClick()" + PDAGlobal.selectPosition + " | " + position);
                if (PDAGlobal.selectPosition != -1) {
                    View child = adapter.getViewByPosition(PDAGlobal.selectPosition, R.id.tvIndex);
                    Log.d("aaaaaa", "onItemClick()" + child);
                    if (child != null) {
                        View oldSelectionView = (View) child.getParent();
                        Goods item = (Goods) adapter.getItem(PDAGlobal.selectPosition);
                        if (item != null) {
                            if (item.getValidation_type() == 1) {
                                oldSelectionView.setBackgroundColor(getResources().getColor(R.color.darkgray));
                            } else {
                                oldSelectionView.setBackgroundColor(getResources().getColor(R.color.colorWhite));
                            }
                        }
                    } else {
                        //如果child已经划出屏幕范围，那么刷新一下，防止convert不会调用的情况存在。
                        adapter.notifyDataSetChanged();
                    }
                    if (position == PDAGlobal.selectPosition) {
                        PDAGlobal.selectPosition = -1;
                        return;
                    }
                }

                PDAGlobal.selectPosition = position;
                view.setBackgroundColor(getResources().getColor(R.color.colorRed));
            }
        });

        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));

        smartRefreshLayout.setEnableRefresh(false);
        //禁止加载更多，有一种情况，就是加载了db的数据后，加载更多的时候会调用网络请求，那么就又会添加一遍，所以干脆就禁止了。
        smartRefreshLayout.setEnableLoadMore(false);
        smartRefreshLayout.setNoMoreData(true);
        smartRefreshLayout.setDisableContentWhenLoading(true);
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                downLoadOrderInfo();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
            }
        });
    }


    @OnClick({R.id.btDownLoad, R.id.btResetting, R.id.btValidation, R.id.btDone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btDownLoad: {
                MProgressDialogHelper.showLoading(this);
                resetData();
                searchOrderInfoFromDB();
                lockEtUnique();
            }
            break;
            case R.id.btResetting: {
                ///重置的意思是清空某一个商品的扫描数据
                if (PDAGlobal.selectPosition == -1) {
                    ToastUtils.showShort("您必须选择一个商品来重置!");
                    return;
                }
                Goods good = orderDetailAdapter.getData().get(PDAGlobal.selectPosition);
                good.setValidation_count(0);
                good.setValidation_type(0);
                good.setFgoods_codes("");
                statisticsSuccessCount();
                orderDetailAdapter.notifyItemChanged(PDAGlobal.selectPosition);
            }
            break;
            case R.id.btValidation: {
                jumpToOrderValidation();
            }
            break;
            case R.id.btDone: {
                submitOrderInfo();
                unlockEtUnique();
            }
            break;
        }
    }

    private void statisticsSuccessCount() {
        int successCount = 0;
        for (Goods goods : orderDetailAdapter.getData()) {
            if (goods.getValidation_type() == 1) {
                successCount++;
            }
        }
        tvSuccessCount.setText("完成行数:" + successCount);
    }

    private void searchOrderInfoFromDB() {
        if (StringUtils.isEmpty(etUniqueID.getText())) {
            MProgressDialog.dismissProgress();
            ToastUtils.showShort("唯一码不能为空");
            return;
        }
        OrderPresenter.searchOrderInfo(etUniqueID.getText().toString(), new OrderDetailSearchFromDBListener(this));
    }


    private void downLoadOrderInfo() {
        if (StringUtils.isEmpty(etUniqueID.getText())) {
            ToastUtils.showShort("唯一码不能为空");
            smartRefreshLayout.finishLoadMore();
            return;
        }
        OrderPresenter.downLoadOrderInfo(etUniqueID.getText().toString(), SPUtils.getInstance().getString("username"), pageIndex, new
                OrderDetailDownLoadListener(this));
    }

    private void submitOrderInfo() {
        if (StringUtils.isEmpty(etUniqueID.getText())) {
            ToastUtils.showShort("唯一码不能为空");
            return;
        }

        if (mOrderInfo == null || mOrderInfo.Data == null) {
            ToastUtils.showShort("订单数据为空,不能提交完成!");
            return;
        }

        boolean isValidationSuccess = true;
        List<Goods> data = orderDetailAdapter.getData();
        for (Goods good : data) {
            if (good.getValidation_count() != good.getFgoods_qty()) {
                isValidationSuccess = false;
            }
        }
        // TODO: 2021/7/6 测试提交接口，需要注意上传的接口，trace code是数组
        if (isValidationSuccess) {
            MProgressDialogHelper.showLoading(this);
            OrderPresenter.submitOrderInfo(data, SPUtils.getInstance().getString("username"), new OrderDetailSubmitListener
                    (this));
        } else {
            ToastUtils.showShort("订单未完成已保存到本地");
            saveOrderInfoToDB();
        }
    }


    private void resetData() {
        mOrderInfo = null;
        smartRefreshLayout.setNoMoreData(false);
        orderDetailAdapter.setNewData(null);
        pageIndex = 0;
        PDAGlobal.selectPosition = -1;
        tvSuccessCount.setText("完成行数:0");
    }

    private void saveOrderInfoToDB() {
        List<Goods> data = orderDetailAdapter.getData();
        for (int i = 0; i < data.size(); i++) {
            Goods good = data.get(i);
            good.setId(good.getForder_id() * 10000 + i);
            good.setPage_index(pageIndex);
        }
        mOrderInfo.setFexa_date(new Date());
        OrderPresenter.insertOrderInfo(mOrderInfo, null);
    }


    private void deleteOrderInfoFromDB() {
        if (mOrderInfo == null) {
            return;
        }
        OrderPresenter.deleteOrderInfo(mOrderInfo.getForder_id(), mOrderInfo.getData(), new DeleteOrderInfoFromDBListener(this));
    }

    private void jumpToOrderValidation() {
        if (orderDetailAdapter.getData().size() == 0) {
            ToastUtils.showShort("没有订单不能进行验证!");
            return;
        }
//        if (PDAGlobal.selectPosition != -1) {
//            Goods item = orderDetailAdapter.getItem(PDAGlobal.selectPosition);
//            if (item != null && item.getValidation_type() == 1) {
//                ToastUtils.showShort("此商品已经验证完毕!");
//                return;
//            }
//        }
        Intent intent = new Intent(this, OrderValidationActivity.class);
        intent.putParcelableArrayListExtra("goods", new ArrayList<Parcelable>(orderDetailAdapter.getData()));
        startActivityForResult(intent, RESULT_CODE);
    }

    public void setUniqueID(String uniqueID) {
        if (!uniqueIDLock) {
            etUniqueID.setText(uniqueID);
            etUniqueID.setSelection(uniqueID.length());
        }
    }

    private void lockEtUnique() {
        uniqueIDLock = true;
        hiddenEt.requestFocus();
    }

    private void unlockEtUnique() {
        uniqueIDLock = false;
    }

    private void validateByScan(String content) {

        if (StringUtils.isTrimEmpty(etUniqueID.getText().toString())) {
            setUniqueID(content);
        } else {
            if (mOrderInfo != null && mOrderInfo.Data != null && mOrderInfo.Data.size() > 0) {
                String traceCode = "";
                String snCode = content;
                if (content.contains("_")) {
                    //追溯
                    String[] split = content.split("_");
                    if (split.length == 2) {
                        snCode = split[0];
                        traceCode = split[1];
                    } else {
                        ToastUtils.showShort("追溯码残缺");
                        return;
                    }
                }
                boolean hasTraceCode = !StringUtils.isTrimEmpty(traceCode);
                List<Goods> targetList = new ArrayList<>();
                for (Goods goods : mOrderInfo.Data) {
                    if (goods.getFgoods_sn() != null && goods.getFgoods_sn().equals(snCode)) {
                        if ((goods.getFiscode() == 1 && hasTraceCode) || (goods.getFiscode() != 1 && !hasTraceCode)) {
                            targetList.add(goods);
                        }
                    }
                }


                if (targetList.size() > 0) {
                    int totalCount = 0;
                    int totalQty = 0;
                    for (Goods goods : targetList) {
                        totalQty += goods.getFgoods_qty();
                        totalCount += goods.getValidation_count();
                    }
                    if (totalQty == 0) {
                        ToastUtils.showShort("数据异常，可扫码数上限是0。");
                        return;
                    }

                    if (totalCount == totalQty) {
                        scanDeviceHelper.speak(3);
                        ToastUtils.showShort("不能超过最大数");
                        return;
                    }

                    Goods targetGoods = findNeedValidateGoods(targetList);

                    if (targetGoods == null) {
                        ToastUtils.showShort("没有找到对应的商品！");
                        return;
                    }


                    if (hasTraceCode) {
                        if (StringUtils.isTrimEmpty(targetGoods.getFgoods_codes())) {
                            targetGoods.setFgoods_codes(traceCode + "_");
                        } else if (!targetGoods.getFgoods_codes().contains(traceCode)) {
                            targetGoods.setFgoods_codes(targetGoods.getFgoods_codes() + traceCode + "_");
                        } else {
                            //如果已经包含了这个追溯码了,就不处理了，跳出逻辑。
                            ToastUtils.showShort("此追溯码已经扫过了");
                            return;
                        }
                    }

                    targetGoods.setValidation_count(targetGoods.getValidation_count() + 1);

                    if (targetGoods.getValidation_count() == targetGoods.getFgoods_qty()) {
                        targetGoods.setValidation_type(1);
                    }

                    int index = orderDetailAdapter.getData().indexOf(targetGoods);
                    recyclerView.scrollToPosition(index);
                    orderDetailAdapter.notifyItemChanged(index);
                    statisticsSuccessCount();
                    scanDeviceHelper.speak(1);
                } else {
                    scanDeviceHelper.speak(2);
                    ToastUtils.showShort("您扫的二维码不是本订单所属的!");
                }
            }
        }
    }

    /**
     * 查找应该验证的商品
     *
     * @param goodsList 应该查找的商品的数组，为何为数组?是因为可能存在同sn的情况。
     * @return 。
     */
    private Goods findNeedValidateGoods(List<Goods> goodsList) {
        for (Goods goods : goodsList) {
            if (goods.getValidation_count() < goods.getFgoods_qty()) {
                return goods;
            }
        }
        return null;
    }


    //</editor-fold>

    //<editor-fold desc=”内部类”>

    /**
     * 下载请求回调
     */
    private static class OrderDetailDownLoadListener implements Presenter.PresenterListener<OrderInfo> {
        private WeakReference<OrderDetailActivity> weakReference;

        public OrderDetailDownLoadListener(OrderDetailActivity context) {
            weakReference = new WeakReference<>(context);
        }

        @Override
        public void onSuccess(OrderInfo object) {
            MProgressDialog.dismissProgress();
            if (weakReference.get() == null) {
                return;
            }

            OrderDetailActivity orderDetailActivity = weakReference.get();

            if (orderDetailActivity.mOrderInfo == null) {
                orderDetailActivity.mOrderInfo = object;
                if (object == null || object.Data == null) {
                    ToastUtils.showShort(object.getMessage());
                    //数据为空的时候 就说明订单没有下载到,所以需要置空
                    orderDetailActivity.mOrderInfo = null;
                }
            } else {
                if (orderDetailActivity.mOrderInfo.Data == null) {
                    orderDetailActivity.mOrderInfo.Data = new ArrayList<>();
                }
                if (object == null || object.Data == null) {
                    orderDetailActivity.smartRefreshLayout.finishLoadMoreWithNoMoreData();
                    return;
                }
                orderDetailActivity.mOrderInfo.Data.addAll(object.Data);
            }

            if (object == null || object.Data == null) {
                orderDetailActivity.smartRefreshLayout.finishLoadMoreWithNoMoreData();
                return;
            }

            if (orderDetailActivity.mOrderInfo != null && orderDetailActivity.mOrderInfo.Data.size() > 0) {
                orderDetailActivity.mOrderInfo.setForder_id(orderDetailActivity.mOrderInfo.Data.get(0).getForder_id());
                orderDetailActivity.mOrderInfo.setForder_sn(orderDetailActivity.mOrderInfo.Data.get(0).getForder_sn());
                orderDetailActivity.mOrderInfo.setForder_date(orderDetailActivity.mOrderInfo.Data.get(0).getFOrderDate());
            }

            if (object.getData().size() != 0) {
                orderDetailActivity.orderDetailAdapter.addData(object.Data);
            }
            orderDetailActivity.smartRefreshLayout.finishLoadMoreWithNoMoreData();

//            if (object.getData().size() < 20) {
//                if (object.getData().size() != 0) {
//                    orderDetailActivity.orderDetailAdapter.addData(object.Data);
//                }
//                orderDetailActivity.smartRefreshLayout.finishLoadMoreWithNoMoreData();
//            } else {
//                orderDetailActivity.orderDetailAdapter.addData(object.Data);
//                orderDetailActivity.smartRefreshLayout.finishLoadMore();
//            }
//            orderDetailActivity.pageIndex++;
        }

        @Override
        public void onError(String error) {
            MProgressDialog.dismissProgress();
            if (weakReference.get() != null) {
                MProgressDialogHelper.showFail(weakReference.get(), "网络链接异常!", null);
            }
        }
    }

    /**
     * 提交请求回调
     */
    private static class OrderDetailSubmitListener implements Presenter.PresenterListener<HashMap> {
        private WeakReference<OrderDetailActivity> weakReference;

        public OrderDetailSubmitListener(OrderDetailActivity context) {
            weakReference = new WeakReference<>(context);
        }

        @Override
        public void onSuccess(HashMap object) {
            MProgressDialog.dismissProgress();
            if (weakReference.get() == null) {
                return;
            }

            OrderDetailActivity orderDetailActivity = weakReference.get();

            boolean flag = (boolean) object.get("Flag");
            if (flag) {
                orderDetailActivity.deleteOrderInfoFromDB();
                ToastUtils.showShort("发货成功");
            } else {
                String message = (String) object.get("Message");
                if (message.contains("订单已出库")) {
                    orderDetailActivity.deleteOrderInfoFromDB();
                    ToastUtils.showShort("发货成功");
                } else {
                    orderDetailActivity.saveOrderInfoToDB();
                    ToastUtils.showShort(message);
                }
            }
        }

        @Override
        public void onError(String error) {
            MProgressDialog.dismissProgress();
            if (weakReference.get() != null) {
                ToastUtils.showShort(error);
            }
        }
    }

    /**
     * 数据库删除回调
     */
    private static class DeleteOrderInfoFromDBListener implements Presenter.PresenterListener<Boolean> {
        private WeakReference<OrderDetailActivity> weakReference;

        public DeleteOrderInfoFromDBListener(OrderDetailActivity context) {
            weakReference = new WeakReference<>(context);
        }

        @Override
        public void onSuccess(Boolean object) {
            if (!object || weakReference.get() == null) {
                return;
            }

            OrderDetailActivity orderDetailActivity = weakReference.get();
            orderDetailActivity.resetData();
        }

        @Override
        public void onError(String error) {
            MProgressDialog.dismissProgress();
            ToastUtils.showShort("数据表删除失败");
        }
    }


    /**
     * 数据库查询回调
     */
    private static class OrderDetailSearchFromDBListener implements Presenter.PresenterListener<OrderInfo> {
        private WeakReference<OrderDetailActivity> weakReference;

        public OrderDetailSearchFromDBListener(OrderDetailActivity context) {
            weakReference = new WeakReference<>(context);
        }

        @Override
        public void onSuccess(OrderInfo object) {
            if (weakReference.get() == null) {
                return;
            }
            OrderDetailActivity orderDetailActivity = weakReference.get();
            if (object == null) {
                orderDetailActivity.downLoadOrderInfo();
                return;
            }
            List<Goods> result = object.getData();

            if (result == null || result.size() == 0) {
                orderDetailActivity.downLoadOrderInfo();
            } else {
                MProgressDialog.dismissProgress();
                orderDetailActivity.mOrderInfo = object;
                orderDetailActivity.pageIndex = 0;
//                orderDetailActivity.pageIndex = result.get(0).getPage_index();
                orderDetailActivity.orderDetailAdapter.addData(result);
                orderDetailActivity.statisticsSuccessCount();
            }
        }

        @Override
        public void onError(String error) {
            MProgressDialog.dismissProgress();
        }
    }


    /**
     * 扫码回调
     */
    private static class ScanValidationListener implements ScanDeviceHelper.ScanDeviceHelperListener {
        private WeakReference<OrderDetailActivity> weakReference;

        public ScanValidationListener(OrderDetailActivity context) {
            this.weakReference = new WeakReference<>(context);
        }

        @Override
        public void onSuccess(String content) {
            if (weakReference.get() == null) {
                return;
            }
            OrderDetailActivity orderDetailActivity = weakReference.get();
            orderDetailActivity.validateByScan(content);
        }
    }


    //</editor-fold>
}
